#include "car.h"

Car::Car(QCustomPlot *_plot, QWidget *parent):QLabel(parent)
{
    this->setStyleSheet("background-color: rgba(255, 255, 255, 0);");
    this->setAlignment(Qt::AlignCenter);
    setCarView(false);
    plot = _plot;
    pos = QPointF(0, 0);
    angle = 0;
    connect(plot, &QCustomPlot::afterReplot, [this](){this->move(plot->xAxis->coordToPixel(pos.x())-(this->width()/2), plot->yAxis->coordToPixel(pos.y())-(this->height()/2));});
//    connect(plot, SImeGNAL(afterReplot()), this, SLOT(updatePosition()));
}

void Car::setPos(QPointF _pos, int ang)
{
    matrix.rotate(ang-angle);
    this->setPixmap(pixCar.transformed(matrix, Qt::SmoothTransformation));
    pos = _pos;
    angle = ang;
    updatePosition();
}

void Car::setPos()
{
    matrix.rotate(angle-angle);
    this->setPixmap(pixCar.transformed(matrix, Qt::SmoothTransformation));
    updatePosition();
}

QPointF Car::getPos()
{
    return pos;
}

void Car::setPixPos(QPoint _pos, int ang)
{
    matrix.rotate(ang-angle);
    this->setPixmap(pixCar.transformed(matrix, Qt::SmoothTransformation));
//    pos = _pos;
    this->move(_pos);
    angle = ang;
}

void Car::setPixPos(QPoint _pos)
{
    this->move(_pos);
}

void Car::setAngle(int ang)
{
    matrix.rotate(ang-angle);
    this->setPixmap(pixCar.transformed(matrix, Qt::SmoothTransformation));
    angle = ang;
}

void Car::setCarView(bool carView)
{
    if(carView)
    {
        int _size = 4*plot->geometry().height()/CAR_VIEW_SIZE;
        qDebug()<<"[car size]"<<_size;
        this->resize(_size,_size);
        pixCar = QPixmap(":/main/image/car0.png");
        pixCar = pixCar.scaled(_size,_size);
        matrix.rotate(0);
        this->setPixmap(pixCar.transformed(matrix, Qt::SmoothTransformation));
    }
    else
    {
        int _size = 40;
        qDebug()<<"[car size]"<<_size;
        this->resize(_size,_size);
        pixCar = QPixmap(":/main/image/car0.png");
        pixCar = pixCar.scaled(_size,_size);
        matrix.rotate(0);
        this->setPixmap(pixCar.transformed(matrix, Qt::SmoothTransformation));
    }
}

void Car::updatePos(QPointF _pos)
{
    pos = _pos;
}

void Car::updatePosition()
{
    qDebug()<<"update"<<pos;
    this->move(plot->xAxis->coordToPixel(pos.x())-(this->width()/2), plot->yAxis->coordToPixel(pos.y())-(this->height()/2));
}
